﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Linq;

using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;
using System.Windows.Resources;
using System.Windows.Markup;
using System.Xml.Serialization;



namespace UnionPay4WP
{
    public partial class UnionPayControl : UserControl,OrderInterface
    {
        /*************************************************************/
        /*                                                           */
        /*                  公共变量 和 公共方法                       */
        /*                                                           */
        /*************************************************************/

        //遮罩
        public Popup popup = new Popup();

        //后台线程
        private BackgroundWorker backroungWorker;

        //调用方 订单信息 存放处
        public static OrderClass order=new OrderClass();

        //以下三个变量，都是从config.xml中取出的：msgTimeout为短信验证码超时时间，其他两个是url地址
        //现在发https请求用的是UPPayServerUrlTest
        //如果传进来的UseTestMode为false，将productUrl的值赋给UPPayServerUrlTest；如果为true，则不作为
        public static string UPPayServerUrlTest = "";
        public static string productUrl = "";
        public static int msgTimeout = 0;

        //记录当前页面的编号
        public static int pivotNum = 0;

        int tempSeconds = 1000;

        public UnionPayControl()
        {
            InitializeComponent();
            Touch.FrameReported += (s, e) =>
            {
                if (e.GetPrimaryTouchPoint(pivot).Action == TouchAction.Up)
                {
                    //pivot.IsHitTestVisible = true;
                    //pivot.IsLocked = false;
                }
            };
        }

        //这个函数在所有
        public void reset()
        {
            pivotNum = 0;
            ServerResponseVars.reset();
            try
            {
                recoverConfig();
                if (order.UseTestMode == false) //若为实际支付场景，则用productUrl发各http请求
                    UPPayServerUrlTest = productUrl;
            }
            catch
            {
                showError("","配置信息不足");
                return;
            }
            try
            {
               recoverSettings();
            }
            catch
            {
                showError("","settings.xml文件错误");
                return;
            }
            if (!order.isValid())
            {
                showError("","订单信息不足");
            }
            else
            {
                payNowButton.IsEnabled = false;
                loadOrderConfirmPivot();

                //开线程 发PayInit的报文
                ShowPopup();
                StartLoadingData();
            }
        }
        private void recoverConfig()
        {
            Uri uri = new Uri("/UnionPay4WP;component/config.xml", UriKind.Relative);
            XElement root = XElement.Load(uri.ToString());
            UPPayServerUrlTest = root.Element("testUrl").Value.ToString();
            productUrl = root.Element("productUrl").Value.ToString();
            msgTimeout = Convert.ToInt32(root.Element("msgTimeout").Value.ToString());/* */
        }
        private void recoverSettings()
        {
            try{
            IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication();

            if (isStore.FileExists("settings.xml"))
            {
                IsolatedStorageFileStream isStream = new IsolatedStorageFileStream("settings.xml", System.IO.FileMode.Open, FileAccess.Read, isStore);
                XElement root = XElement.Load(isStream);
                Setting.account = root.Element("account").Value.ToString();
                Setting.phoneNum = root.Element("phoneNum").Value.ToString();
                Setting.remember = root.Element("remember").Value;
                Setting.accountUniqueID = root.Element("accountUniqueID").Value.ToString();
                Setting.limitMonth = root.Element("limitMonth").Value.ToString();
                Setting.limitYear = root.Element("limitYear").Value.ToString();
                Setting.issuerName = root.Element("issuerName").Value.ToString();
                Setting.cardType = root.Element("cardType").Value.ToString();
                Setting.LimitedAmount = root.Element("LimitedAmount").Value.ToString();
                isStream.Close();
            }
            else
            {
               // showError("","此方法不通");
            }
            }
            catch{}
        }



        /*************************************************************/
        /*                                                           */
        /*                以下3个函数禁用 Pivot 切换手势                 */
        /*                                                           */
        /*************************************************************/
        /*
                private void controlManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
                {
                    e.Handled = true;
                   // pivot.IsHitTestVisible = true;
                }

                private void controlManipulationDelta(object sender, ManipulationDeltaEventArgs e)
                {
                    e.Handled = true;
                }

                private void controlManipulationStarted(object sender, ManipulationStartedEventArgs e)
                {
                    e.Handled = true;
                   // pivot.IsHitTestVisible = false;
                    //pivot.IsLocked = true;
                }

                 */
        //private void manipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        //{
        //    e.Handled = true;
        //}

        //private void manipulationDelta(object sender, ManipulationDeltaEventArgs e)
        //{
        //    e.Handled = true;
        //}

        //private void manipulationStarted(object sender, ManipulationStartedEventArgs e)
        //{
        //    e.Handled = true;
        //}

       

        /*************************************************************/
        /*                                                           */
        /*                外部向控件传值(传给order)                    */
        /*                                                           */
        /*************************************************************/
        public void setAppName(string an) { order.AppName = an; }
        public void setVersion(string v) { order.Version = v; }
        public void setMerchantSummary(string ms) { order.MerchantSummary = ms; }
        public void setResultUri(string ru) { order.ResultUri = ru; }
        public void setTransCurrency(string tc) { order.TransCurrency = tc; }
        public void setType(string t) { order.Type = t; }
        public void setOrderId(string oi) { order.OrderId = oi; }
        public void setMerchantName(string mn) { order.MerchantName = mn; }
        public void setSignature(string s) { order.Signature = s; }
        public void setServiceInfo(string si) { order.ServiceInfo = si; }
        public void setSpId(string si) { order.SpId = si; }
        public void setSysProvided(string sp) { order.SysProvide = sp; }
        public void setTerminalId(string ti) { order.TerminalId = ti; }
        public void setTransAmount(string ta) { order.TransAmountStr = ta; order.TransAmount = Convert.ToInt32(ta); }
        public void setMerchantId(string mi) { order.MerchantId = mi; }
        public void setMerchantCountry(string mc) { order.MerchantCountry = mc; }
        public void setOrderContent(string oc) { order.OrderContent = oc; }
        public void setUseTestMode(bool utm) { order.UseTestMode = utm; }
        public void setContentProvide(string cp) { order.ContentProvide = cp; }
        public void setUserProvide(string up) { order.UserProvide = up; }
        public bool isValid() { return order.isValid(); }
        public void setAccountNumber2(string an2) { order.AccountNumber2 = an2; }
        public void setSubmitTime(string st)
        {
            order.SubmitTime = st;
            int year = Convert.ToInt32(order.SubmitTime.Substring(0, 4));
            int month = Convert.ToInt32(order.SubmitTime.Substring(4, 2));
            int day = Convert.ToInt32(order.SubmitTime.Substring(6, 2));
            int hour = Convert.ToInt32(order.SubmitTime.Substring(8, 2));
            int minute = Convert.ToInt32(order.SubmitTime.Substring(10, 2));
            int second = Convert.ToInt32(order.SubmitTime.Substring(12, 2));
            order.SubmitTime_dt = new DateTime(year, month, day, hour, minute, second);
        }
        public void release()
        {
            try
            {
                order = new OrderClass();
                popup.IsOpen = false;

            }
            catch { }

        }



        /*************************************************************/
        /*                                                           */
        /*                          错误处理                          */
        /*                                                           */
        /*************************************************************/

        //根据错误码，从error.xml中查出错误含义，再显示在errorCanvas上
        public void NavigateToError(string errorCode)
        {
            if (errorCode == "00000")
                errorCode = ServerResponseVars.MsgResponseCode;
            Error err = new Error();
            string meaning = "未知错误";
            try
            {
                meaning = errorTranslator.translate(errorCode, ref err);
            }
            catch { }
            //showError("错误编码："+errorCode,"错误含义："+meaning);
            showError(" ", meaning + ", " + errorCode);
        }

        //将errorCode和errorMeaning显示在errorCanvas上
        private void showError(string errorCode, string errorMeaning)
        {
            errorCodeTextBlock.Text = errorCode;
            errorMeaningTextBlock.Text = errorMeaning;
            errorCanvas.Visibility = Visibility.Visible;
        }
        //errorCanvas上的“取消”
        private void errorCancelButton_Click(object sender, RoutedEventArgs e)
        {
            errorCanvas.Visibility = Visibility.Collapsed;
        }
        //errorCanvas上的“退出程序”
        private void errorExitButton_Click(object sender, RoutedEventArgs e)//不知道可不可以哈
        {
            //this.Visibility = Visibility.Collapsed;
            release();
            Return("fail");
        }




        /*************************************************************/
        /*                                                           */
        /*                       遮罩&后台线程                        */
        /*                                                           */
        /*************************************************************/

        //显示遮罩
        private void ShowPopup()
        {
            this.popup = new Popup();
            this.popup.Child = new PopupSplash("请稍等......");
            this.popup.IsOpen = true;
        }
        //以下两个函数 请求支持的银行 bankSupport
        private void StartLoadingBankList()
        {
            backroungWorker = new BackgroundWorker();
            backroungWorker.DoWork += new DoWorkEventHandler(bankListBackroungWorker_DoWork);
            backroungWorker.RunWorkerAsync();
        }
        void bankListBackroungWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            XmlRequestBuilder xmlBuilder = new XmlRequestBuilder();
            string xmlString = xmlBuilder.bankSupportEnquiry();
            string unionUrl = UPPayServerUrlTest;
            HttpPost(unionUrl, xmlString);
        }

        //以下两个函数 发其他页面切换之前的请求
        //包括 payInit cardInfoQuery cardTransInfo sMSVerification purchase
        private void StartLoadingData()
        {
            backroungWorker = new BackgroundWorker();
            backroungWorker.DoWork += new DoWorkEventHandler(backroungWorker_DoWork);
            backroungWorker.RunWorkerAsync();
        }
        void backroungWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            XmlRequestBuilder xmlBuilder = new XmlRequestBuilder();
            string xmlString = "";
            switch (pivotNum)
            {
                case 0:
                    xmlString = xmlBuilder.payInit();
                    break;
                case 1:case 7:
                    xmlString = xmlBuilder.cardInfoEnquiry(ServerResponseVars.account, ServerResponseVars.phoneNum, ServerResponseVars.checkCode);//这里传了参数
                    break;
                case 2:case 3:
                    xmlString = xmlBuilder.purchase();
                    break;
            }
            if (xmlString == "")
            {
            }
            string unionUrl = UPPayServerUrlTest;
            HttpPost(unionUrl, xmlString);
        }

        /*************************************************************/
        /*                                                           */
        /*                       发Https请求                          */
        /*                                                           */
        /*************************************************************/
        private string xmlRequest = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<cupMobiles>
	<cupMobile application=""UPNoCard"" version=""1.01"">
		<transaction type=""BankSupportEnquiry.APReq"">
			<sessionID>a6bfa12afa0a4fb19564012e02228556</sessionID>
		</transaction>
	</cupMobile>
</cupMobiles>
";
        /// <summary>
        /// 异步Post请求
        /// </summary>
        public void HttpPost(string url, string xml)
        {
            try
            {
                //创建WebRequest类
                HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(url));
                xmlRequest = xml;
                request.Method = "POST";
                request.ContentType = "application/xml";
                request.Accept = "application/xml";
                request.BeginGetRequestStream(requestCallback, request);//
            }catch (WebException e){ }catch { }
        }

        /// <summary>
        /// 发送异步Post请求
        /// </summary>
        /// <param name="result"></param>
        private void requestCallback(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(xmlRequest);
                Stream postStream = request.EndGetRequestStream(result);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                postStream.Dispose();
                //返回应答请求异步操作的状态
                request.BeginGetResponse(responseCallback, request);
            }
            catch { }
        }
        /// <summary>
        /// 异步获取Post的相应流
        /// </summary>
        /// <param name="result"></param>
        private void responseCallback(IAsyncResult result)
        {
            try
            {
                //获取异步操作返回的的信息
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                //解析应答头
                //parseRecvHeader(response.Headers);
                //获取请求体信息长度
                long contentLength = response.ContentLength;
                //获取应答码
                int statusCode = (int)response.StatusCode;
                string statusText = response.StatusDescription;
                //string nextUri = null;
                int nextUri = 0;
                //应答头信息验证
                using (Stream stream = response.GetResponseStream())
                {
                    //获取请求信息
                    try
                    {

                        StreamReader read = new StreamReader(stream);
                        string msg = read.ReadToEnd();
                        XmlResponseParser xmlParser = new XmlResponseParser();
                        if (xmlParser.parse(msg, out nextUri))
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                try
                                {
                                    if (pivot.IsLocked)
                                        pivot.IsLocked = false;
                                popup.IsOpen = false;
                                switch (nextUri)
                                {
                                    case 0: payNowButton.IsEnabled = true; break;
                                    case 1: loadSelectCardPivot(); break;
                                    case 2: loadCardInfoPivot(); break;
                                    case 3: loadCardInfo2Pivot(); break;
                                    case 4: loadResultPivot(); break;
                                    case 5: ShowBanksShort(); break;
                                    case 7: loadCardInfo3Pivot(); break;
                                }

                                    pivot.SelectedIndex = nextUri;
                                    pivotNum = nextUri;
                                }
                                catch { }
                                finally
                                {
                                    pivot.IsLocked = true;
                                }

                            });

                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                //pivot.IsLocked = false;
                                //pivot.SelectedIndex = 6;
                                popup.IsOpen = false;
                                NavigateToError(ServerResponseVars.TransResponseCode);
                                

                            });
                        }
                        ;
                    }
                    catch (Exception e)
                    {
                        // popup.IsOpen = false;
                    }


                }

            }
            catch (WebException e)
            {
                
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    popup.IsOpen = false;
                     showError("","网络连接错误");
                });
            } catch {}
        }



        /*************************************************************/
        /*                                                           */
        /*               orderConfirmPivot上的按钮                    */
        /*                                                           */
        /*************************************************************/     
        private void PayNowButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                int limit = Convert.ToInt32(OrderClass.LimitedAmount);
                //if ("" != Setting.accountUniqueID && order.TransAmount < limit)
                //{
                //    if ("CreditCard" == ServerResponseVars.cardType || "CreditCard" == Setting.cardType)
                //    {
                //        pivotNum = 2;
                //        loadCardInfoPivot();
                //        pivot.SelectedItem = cardInfoPivot;
                //    }
                //    else
                //    {
                //        pivotNum = 3;
                //        loadCardInfo2Pivot();
                //        pivot.SelectedItem = cardInfo2Pivot;
                //    }
                //}
                //else
                //{
                //    pivotNum = 1;
                //    loadSelectCardPivot();
                //    pivot.SelectedItem = selectCardPivot;
                //}
                if ("" != Setting.accountUniqueID) 
                {
                    if (order.TransAmount < limit)
                    {
                        if ("CreditCard" == ServerResponseVars.cardType || "CreditCard" == Setting.cardType)
                        {
                            pivotNum = 2;
                            loadCardInfoPivot();
                            pivot.SelectedItem = cardInfoPivot;
                        }
                        else
                        {
                            pivotNum = 3;
                            loadCardInfo2Pivot();
                            pivot.SelectedItem = cardInfo2Pivot;
                        }
                    }
                    else
                    {
                        pivotNum = 7;
                        loadCardInfo3Pivot();
                        pivot.SelectedItem = cardInfoEnquiryPivot;
                    }
                }
                else
                {
                    pivotNum = 1;
                    loadSelectCardPivot();
                    pivot.SelectedItem = selectCardPivot;
                }
            }
            catch { }
            finally
            {
                pivot.IsLocked = true;
            }
        }
        private void PayLaterButton_Click(object sender, RoutedEventArgs e)
        {
            showError("", "确定取消支付吗？");
        }




        /*************************************************************/
        /*                                                           */
        /*                    selectCardPivot上的行为                 */
        /*                                                           */
        /*************************************************************/

        Stopwatch stopWatch = new Stopwatch();
        TimeSpan suspensionAdjustment = new TimeSpan();
        private void accountButton_Click(object sender, RoutedEventArgs e)
        {
            ShowPopup();
            StartLoadingBankList();
        }
        private void getCheckCode_Click(object sender, RoutedEventArgs e)
        {
            if (11 != phoneNumberTextBox.Text.Length || !StringPlus.IsAllNumber(phoneNumberTextBox.Text))
            {
                showError( "","在银行预留的手机号码错误，请重新输入");
            }
            else
            {
                ShowPopup();
                startTimer();
                XmlRequestBuilder xmlBuilder = new XmlRequestBuilder();
                ServerResponseVars.phoneNum = phoneNumberTextBox.Text;
                string xmlString = xmlBuilder.sMSGenerate(ServerResponseVars.phoneNum);
                string unionUrl = UPPayServerUrlTest;
                HttpPost(unionUrl, xmlString);
            }
        }

        private void startTimer()
        {
            stopWatch.Start();
            getCheckCodeButton.IsEnabled = false;
            getCheckCodeButton2.IsEnabled = false;
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
        private void stopTimer()
        {
            stopWatch.Stop();
            stopWatch.Reset();
            getCheckCodeButton.IsEnabled = true;
            getCheckCodeButton2.IsEnabled = true;
            CompositionTarget.Rendering -= CompositionTarget_Rendering;
        }
        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            DisplayTime();
        }
        void DisplayTime()
        {
            TimeSpan elapsedTime = stopWatch.Elapsed + suspensionAdjustment;
            string str = null;
            
            int remaindSeconds=msgTimeout - elapsedTime.Seconds;
            //if (remaindSeconds.)
            if (tempSeconds != remaindSeconds)
            {
                str = string.Format("{0:D2} 秒", remaindSeconds);

                tempSeconds = remaindSeconds;
                getCheckCodeButton.Content = str;
                getCheckCodeButton2.Content = str;
            }
            //str = (msgTimeout - elapsedTime.Seconds).ToString() + " 秒";
            //getCheckCodeButton.Content = str;
            //getCheckCodeButton2.Content = str;
            if (elapsedTime.Seconds > 58)
            {
                stopTimer();
                getCheckCodeButton.Content = "获取验证码";
                getCheckCodeButton2.Content = "获取验证码";

            }
        }
        private void back2OderButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                pivotNum = 0;
                pivot.SelectedItem = orderConfirmPivot;
            }
            catch { }
            finally
            {
                pivot.IsLocked = true;
            }
        }
        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            if ((0 == accountTextBox.Text.Length)||( accountTextBox.Text == "请输入银行卡号"))
            {
                showError("", "请输入银行卡卡号");
            }
            else if ((0 == phoneNumberTextBox.Text.Length) || (phoneNumberTextBox.Text == "请输入预留手机号"))
            {
                showError("", "请输入在银行预留的手机号");
            }
            else if ((checkCodeTextBox.Visibility == Visibility.Visible) &&((0 == checkCodeTextBox.Text.Length)||(checkCodeTextBox.Text == "请输入验证码")))
            {
                showError("", "请输入短信验证码");
            }
            else if (16 != accountTextBox.Text.Length && 19 != accountTextBox.Text.Length || !StringPlus.IsAllNumber(accountTextBox.Text))
            {
                showError("","银行卡卡号错误，请重新输入");
            }
            else if (11 != phoneNumberTextBox.Text.Length || !StringPlus.IsAllNumber(phoneNumberTextBox.Text))
            {
                showError("", "在银行预留的手机号错误，请重新输入");
            }
            else if ((checkCodeTextBox.Visibility == Visibility.Visible) && (6 != checkCodeTextBox.Text.Length || !StringPlus.IsAllNumber(checkCodeTextBox.Text)))
            {
                showError("", "短信验证码错误，请重新输入");
            }
            else if (!agreeCheckBox.IsChecked.Value)
            {
                showError("", "请阅读用户协议，并同意");
            }
            else
            {
                ShowPopup();
                ServerResponseVars.account = accountTextBox.Text.Trim();
                ServerResponseVars.phoneNum = phoneNumberTextBox.Text.Trim();
                ServerResponseVars.checkCode = checkCodeTextBox.Text.Trim();
                StartLoadingData();
            }
        }

        //保存了卡号（7号页面）的逻辑
        private void nextButton_Click2(object sender, RoutedEventArgs e)
        {
             if ((checkCodeTextBox2.Visibility == Visibility.Visible) && ((0 == checkCodeTextBox2.Text.Length) || (checkCodeTextBox2.Text == "请输入验证码")))
            {
                showError("", "请输入短信验证码");
            }
            else if ((checkCodeTextBox2.Visibility == Visibility.Visible) && (6 != checkCodeTextBox2.Text.Length || !StringPlus.IsAllNumber(checkCodeTextBox2.Text)))
            {
                showError("", "短信验证码错误，请重新输入");
            }
            else
            {
                ShowPopup();
                ServerResponseVars.account = accountTextBox.Text.Trim();
                ServerResponseVars.phoneNum = phoneNumberTextBox.Text.Trim();
                ServerResponseVars.checkCode = checkCodeTextBox2.Text.Trim();
                StartLoadingData();
            }
        }
        private void accountTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

            Setting.account = accountTextBox.Text;
        }
        private void phoneNumberTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Setting.phoneNum = phoneNumberTextBox.Text;
        }
        private void checkCodeTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Setting.checkCode = checkCodeTextBox.Text;
        }
        private void checkCodeTextBox_TextChanged2(object sender, TextChangedEventArgs e)
        {
            Setting.checkCode = checkCodeTextBox2.Text;
        }
        
        
        private void accountTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ("" == accountTextBox.Text)
            {
                accountTextBox.Text = "请输入银行卡号";
            }
            Setting.accountUniqueID = "";
            Setting.LimitedAmount = "";
            Setting.cardType = "";
            Setting.issuerName = "";
            ServerResponseVars.cardType = "";
            ServerResponseVars.LimitedAmout = "";
            ServerResponseVars.issuerName = "";
            
        }
        private void phoneNumberTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ("" == phoneNumberTextBox.Text)
            {
                phoneNumberTextBox.Text = "请输入预留手机号";
            }
        }
        private void checkCodeTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ("" == checkCodeTextBox.Text)
            {
                checkCodeTextBox.Text = "请输入验证码";
            }
            if ("" == checkCodeTextBox2.Text)
            {
                checkCodeTextBox2.Text = "请输入验证码";
            }
        }
        private void accountTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if ("请输入银行卡号" == accountTextBox.Text)
            {
                accountTextBox.Text = "";
            }
        }
        private void phoneNumberTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if ("请输入预留手机号" == phoneNumberTextBox.Text)
            {
                phoneNumberTextBox.Text = "";
            }
        }
        private void checkCodeTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if ("请输入验证码" == checkCodeTextBox.Text)
            {
                checkCodeTextBox.Text = "";
            }
            if ("请输入验证码" == checkCodeTextBox2.Text)
            {
                checkCodeTextBox2.Text = "";
            }
        }




        /*************************************************************/
        /*                                                           */
        /*                    cardInfoPivot上的行为                   */
        /*                                                           */
        /*************************************************************/
        private void backButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //if (pivot.IsLocked)
                //    pivot.IsLocked = false;
                //pivotNum = 1;
                //loadSelectCardPivot();
                //pivot.SelectedItem = selectCardPivot;
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                if (Setting.accountUniqueID != "")
                {
                    pivotNum = 0;
                    pivot.SelectedItem = orderConfirmPivot;
                }
                else
                {
                    pivotNum = 1;
                    loadSelectCardPivot();
                    pivot.SelectedItem = selectCardPivot;
                }
            }
            catch { }
            finally
            {
                pivot.IsLocked = true;
            }
        }

        private void confirmPayButton_Click(object sender, RoutedEventArgs e)
        {
            int len = 3;
            PasswordBox pb;
            if (3 == pivot.SelectedIndex)
            {
                len = 6;
                pb = CVN2PasswdBox;
            }
            else
            {
                len = 3;
                pb = CVN2PasswordBox;
            }
            if (len == pb.Password.Length)
            {
                OrderClass.pin = pb.Password;
                if (3 == len)
                {
                    try
                    {
                        if ("" == limitMonthTextBox.Text || "" == limitYearTextBox.Text || Convert.ToInt16(limitMonthTextBox.Text) > 12 || Convert.ToInt16(limitYearTextBox.Text) < 13)
                        {
                            showError("", "请填写正确的有效日期");
                        }
                        else
                        {
                            OrderClass.date = limitYearTextBox.Text.Length < 2 ? "0" + limitYearTextBox.Text : limitYearTextBox.Text;
                            OrderClass.date += limitMonthTextBox.Text.Length < 2 ? "0" + limitMonthTextBox.Text : limitMonthTextBox.Text;
                            ShowPopup();
                            StartLoadingData();
                        }
                    }
                    catch
                    {
                        showError("", "请填写正确的有效日期");
                    }
                }
                else
                {
                    try
                    {
                        if (Convert.ToInt32(OrderClass.pin) > 0)
                        {
                            ShowPopup();
                            StartLoadingData();
                        }
                        else
                        {
                            showError("", "请输入正确的6位数字密码");
                        }

                    }
                    catch
                    {
                        showError("", "请输入正确的6位数字密码");
                    }
                }
            }
            else
            {
               string text = "";
               if(3==len) text = "CVN2长度为3";
               else if(6==len)text= "借记卡、预付卡的密码为6位";
               showError("", text);
            }
        }
        private void tipButton_Click(object sender, RoutedEventArgs e)
        {
            tipCanvas.Visibility = Visibility.Visible;
        }
        private void tipCanvas_KeyDown(object sender, KeyEventArgs e)
        {
            tipCanvas.Visibility = Visibility.Collapsed;
        }
        private void tipCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            tipCanvas.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void limitYearTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Setting.limitYear = limitYearTextBox.Text;
        }
        private void limitMonthTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Setting.limitMonth = limitMonthTextBox.Text;
        }
        private void CVN2TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            
            CVN2TextBox.Visibility = Visibility.Collapsed;
            CVN2PasswordBox.Visibility = Visibility.Visible;
            CVN2PasswordBox.Focus();
        }
        private void changeCardButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                Setting.accountUniqueID = "";
                Setting.LimitedAmount = "";
                Setting.cardType = "";
                Setting.issuerName = "";
                accountTextBox.Text = "请输入银行卡号";
                phoneNumberTextBox.Text = "请输入预留手机号";
                pivotNum = 1;
                loadSelectCardPivot();
                pivot.SelectedItem = selectCardPivot;
            }
            catch { }
            finally {
                pivot.IsLocked = true;

            }
        }
        private void CVN2PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            //if (CVN2PasswordBox.Password!="")
            if (CVN2PasswordBox.Password.Length==3)
            {
                try
                {
                    if (Convert.ToInt32(CVN2PasswordBox.Password) < 1000)
                        OrderClass.pin = CVN2PasswordBox.Password;
                    else
                        showError("", "请输入正确的CVN2");
                }
                catch
                {
                    showError("", "请输入由3位数字组成的CVN2");
                }
            }
        }
        private void CVN2PasswordBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ("" == CVN2PasswordBox.Password)
            {
                CVN2PasswordBox.Visibility = Visibility.Collapsed;
                CVN2TextBox.Visibility = Visibility.Visible;
            }
        }



        /*************************************************************/
        /*                                                           */
        /*                    cardInfo2Pivot上的行为                   */
        /*                                                           */
        /*************************************************************/
        private void backButton2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                if (Setting.accountUniqueID != "")
                {
                    pivotNum = 0;
                    pivot.SelectedItem = orderConfirmPivot;
                }
                else
                {
                    pivotNum = 1;
                    loadSelectCardPivot();
                    pivot.SelectedItem = selectCardPivot;
                }
            }
            catch { }
            finally
            {
                pivot.IsLocked = true;
            }
        }

        private void CVN2PasswdBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ("" == CVN2PasswdBox.Password)
            {
                CVN2PasswdBox.Visibility = Visibility.Collapsed;
                CVN2TextBox2.Visibility = Visibility.Visible;
            }
        }

        private void CVN2TextBox2_GotFocus(object sender, RoutedEventArgs e)
        {
            CVN2TextBox2.Visibility = Visibility.Collapsed;
            CVN2PasswdBox.Visibility = Visibility.Visible;
            CVN2PasswdBox.Focus();
        }



        /*************************************************************/
        /*                                                           */
        /*                      resultPivot上的行为                   */
        /*                                                           */
        /*************************************************************/

        //将Setting中的内容保存到settings.xml文件中
        private void Restore()
        {
            try
            { 
                if (false == RememberCheckBox.IsChecked)
                {
                    Setting.account = "";
                    Setting.phoneNum = "";
                    Setting.remember = "";
                    Setting.limitMonth = "";
                    Setting.limitYear = "";
                    Setting.accountUniqueID = "";
                    Setting.issuerName = "";
                    Setting.cardType = "";
                    Setting.LimitedAmount = "";
                }
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("settings.xml", System.IO.FileMode.Create, isoStore);
                using (XmlWriter xw = XmlWriter.Create(isoStream))
                {
                    XElement xele = new XElement("settings",
                                           new XElement("account", Setting.account),
                                           new XElement("phoneNum", Setting.phoneNum),
                                           new XElement("remember", Setting.remember),
                                           new XElement("limitMonth", Setting.limitMonth),
                                           new XElement("limitYear", Setting.limitYear),
                                           new XElement("accountUniqueID", Setting.accountUniqueID),
                                           new XElement("issuerName", Setting.issuerName),
                                           new XElement("LimitedAmount", Setting.LimitedAmount),
                                           new XElement("cardType", Setting.cardType));
                    XDocument xdoc = new XDocument(xele);
                    xdoc.Save(xw);
                }
                isoStream.Close();
                isoStore.Dispose();
                release();
            }
            catch (Exception e) {  }
           
        }
        private void RememberCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Setting.remember = RememberCheckBox.IsChecked.ToString();
        }
        
        private void ReturnButton_Click(object sender, RoutedEventArgs e)
        {
            Restore();
            //this.Visibility = Visibility.Collapsed;
            Return("success");//放在代码的最后来实现
        }



        /*************************************************************/
        /*                                                           */
        /*                    bankListPivot上的行为                   */
        /*                                                           */
        /*************************************************************/
        private void ShowBanksShort()//调用这页的时候，首先执行这一行，每种银行显示三个
        {
            //先将控件的样式加入到调用它的应用程序中
          //  ResourceDictionary rd = new ResourceDictionary();
          //  Application.LoadComponent(rd, new Uri("/UnionPay4WP;component/CustomTheme.xaml", UriKind.Relative));
          //  Application.Current.Resources.MergedDictionaries.Add(rd);
            DebitCardHyperLinkButton.Content = "展开...";
            CreditCardHyperLinkButton.Content = "展开...";
            PrepaidCardHyperLinkButton.Content = "展开...";
            DisplayBank(ServerResponseVars.debitBankList, DebitCardStackPanel);
            DisplayBank(ServerResponseVars.creditBankList, CreditCardStackPanel);
            DisplayBank(ServerResponseVars.prepayBankList, PrepaidCardStackPanel);
        }
        private void DisplayBank(string[] bankList, StackPanel Panel)
        {
            int i;
            int listLength;
            Panel.Children.Clear();
            listLength = bankList.Length;
            var textblock = new TextBlock();
            textblock.Style = Application.Current.Resources["CustomTextBlockBase"] as Style;
            textblock.Foreground = PrepaidCardHyperLinkButton.Foreground;
            string str="";
            if (listLength > 3)
                listLength = 3;
            if (listLength > 0)
            {

                for (i = 0; i < listLength; i++)
                {
                    str = str
                        + bankList[i] + "\r\n";

                    textblock.Text = str;//bankList[i]; 



                }

            }
            try
            {

                Panel.Children.Add(textblock);
            }
            catch { }
           // Panel.Background = errorMask.Background;
        }
        private void DebitCardHyperLinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (DebitCardHyperLinkButton.Content.ToString() == "展开...")
            {
                string textLine = "";
                DebitCardStackPanel.Children.Clear();
                var textblock = new TextBlock();
                //textblock.Text = str;
                textblock.Style = Application.Current.Resources["CustomTextBlockBase"] as Style;
                textblock.Foreground = PrepaidCardHyperLinkButton.Foreground;
                foreach (string str in ServerResponseVars.debitBankList)
                {
                    //var textblock = new TextBlock();
                    if ((textLine + str).Length < 25)
                    {

                        textblock.Text = textblock.Text + string.Format("{0,-10}", str);
                        textLine = textLine + string.Format("{0,-10}", str);
                    }
                    else
                    {
                        textblock.Text = textblock.Text + "\r\n" + string.Format("{0,-10}", str);
                        textLine = string.Format("{0,-10}", str);
                    }
                    //textblock.Style = Application.Current.Resources["CustomTextBlockBase"] as Style;
                    //textblock.Foreground = PrepaidCardHyperLinkButton.Foreground;
                    //for (i = 0; i < 30; i++)
                    
                        //DebitCardStackPanel.Children.Add(i);

                }
                DebitCardStackPanel.Children.Add(textblock);
                //for (i = 0; i < 100; i++)
                //{
                //    var textblock = new TextBlock();
                //    textblock.Text = i.ToString();
                //    DebitCardStackPanel.Children.Add(textblock);
                //}


                DebitCardStackPanel.Visibility = Visibility.Visible;
              //  DebitCardStackPanel.Background = LayoutRoot.Background;
                DebitCardHyperLinkButton.Content = "收起...";
            }
            else
                if (DebitCardHyperLinkButton.Content.ToString() == "收起...")
                {
                    DebitCardStackPanel.Children.Clear();
                    DebitCardStackPanel.Visibility = Visibility.Collapsed;
                    DebitCardHyperLinkButton.Content = "展开...";
                }
        }
        private void CreditCardHyperLinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (CreditCardHyperLinkButton.Content.ToString() == "展开...")
            {
                string textLine = "";
                CreditCardStackPanel.Children.Clear();
                var textblock = new TextBlock();
                //textblock.Text = str;
                textblock.Style = Application.Current.Resources["CustomTextBlockBase"] as Style;
                textblock.Foreground = PrepaidCardHyperLinkButton.Foreground;
                foreach (string str in ServerResponseVars.creditBankList)
                {
                    if ((textLine + str).Length < 25)
                    {

                        textblock.Text = textblock.Text + string.Format("{0,-10}", str);
                        textLine = textLine + string.Format("{0,-10}", str);
                    }
                    else
                    {
                        textblock.Text = textblock.Text + "\r\n" + string.Format("{0,-10}", str);
                        textLine = string.Format("{0,-10}", str);
                    }
                    
                   // CreditCardStackPanel.Background = errorMask.Background;
                }
                CreditCardStackPanel.Children.Add(textblock);
                CreditCardStackPanel.Visibility = Visibility.Visible;
                CreditCardHyperLinkButton.Content = "收起...";
            }
            else
                if (CreditCardHyperLinkButton.Content.ToString() == "收起...")
                {
                    CreditCardStackPanel.Children.Clear();
                    CreditCardStackPanel.Visibility = Visibility.Collapsed;
                    CreditCardHyperLinkButton.Content = "展开...";
                }
        }
        private void PrepaidCardHyperLinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (PrepaidCardHyperLinkButton.Content.ToString() == "展开...")
            {
                string textLine = "";
                PrepaidCardStackPanel.Children.Clear();
                var textblock = new TextBlock();
                //textblock.Text = str;
                textblock.Style = Application.Current.Resources["CustomTextBlockBase"] as Style;
                textblock.Foreground = PrepaidCardHyperLinkButton.Foreground;
                foreach (string str in ServerResponseVars.prepayBankList)
                {
                    if ((textLine + str).Length < 25)
                    {

                        textblock.Text = textblock.Text + string.Format("{0,-10}", str);
                        textLine = textLine + string.Format("{0,-10}", str);
                    }
                    else
                    {
                        textblock.Text = textblock.Text + "\r\n" + string.Format("{0,-10}", str);
                        textLine = string.Format("{0,-10}", str);
                    }
                    
                   // PrepaidCardStackPanel.Background = LayoutRoot.Background;
                }
                PrepaidCardStackPanel.Children.Add(textblock);
                PrepaidCardStackPanel.Visibility = Visibility.Visible;
                PrepaidCardHyperLinkButton.Content = "收起...";
            }
            else
                if (PrepaidCardHyperLinkButton.Content.ToString() == "收起...")
                {
                    PrepaidCardStackPanel.Children.Clear();
                    PrepaidCardStackPanel.Visibility = Visibility.Collapsed;
                    PrepaidCardHyperLinkButton.Content = "展开...";
                }
        }


        
        /*************************************************************/
        /*                                                           */
        /*     各个页面切换时，将数据从Setting中或者Order中拿到UI上      */
        /*                                                           */
        /*************************************************************/
        private void loadOrderConfirmPivot()
        {
            //orderConfirmPivot
            merchantNameTextBlock.Text = order.MerchantName;
            amountPayableTextBlock.Text = (order.TransAmount / 100).ToString() + "." + order.TransAmountStr.Substring(order.TransAmountStr.Length - 2, 2) + "元";
            orderNumberTextBlock.Text = order.OrderId;
            purchaseTimeTextBlock.Text = order.SubmitTime_dt.ToString("yyyy-MM-dd");

            //selectCardPivot
            accountTextBox.Text = (Setting.account==""?"请输入银行卡号":Setting.account);
            phoneNumberTextBox.Text = (Setting.phoneNum==""?"请输入预留手机号":Setting.phoneNum);

            //cardInfoPivot cardInfo2Pivot
            MerchantNameTextBlock.Text = order.MerchantName;
            AmountPayableTextBlock.Text = (order.TransAmount / 100).ToString() + "." + order.TransAmountStr.Substring(order.TransAmountStr.Length - 2, 2) + "元";
            orderNumberTextBlock.Text = order.OrderId;
            PurchaseTime.Text = order.SubmitTime_dt.ToString("yyyy-MM-dd");

            //limitMonthTextBox.Text = Setting.limitMonth;
           // limitYearTextBox.Text = Setting.limitYear;
            bankTextBlock2.Text = bankTextBlock.Text = Setting.issuerName;
            if (Setting.LimitedAmount != "")
            {
                int tempint = Convert.ToInt32(Setting.LimitedAmount), len = Setting.LimitedAmount.Length;
                tradeLimitTextBlock.Text = "剩余交易限额：" + (tempint / 100) + "." + Setting.LimitedAmount.Substring(len - 2, 2) + "元";
            }
            
            string tempString = Setting.cardType;
            if ("CreditCard" == tempString) tempString= "(信用卡)";
            else if ("DebitCard" == tempString) tempString= "(借记卡)";
            else if ("PrepaidCard" == tempString) tempString= "(储值卡)";
            else tempString= "(未知类型卡)";
            bankTextBlock.Text += tempString;
            bankTextBlock2.Text += tempString;


            //resultPivot
            Boolean isChecked=false;
            try
            {
                isChecked = Convert.ToBoolean(Setting.remember);
            }
            catch
            {

            }
            RememberCheckBox.IsChecked = isChecked;
            MerchantNameTextBlock.Text = order.MerchantName;
            AmountPayableTextBlock.Text = (order.TransAmount / 100).ToString() + "." + order.TransAmountStr.Substring(order.TransAmountStr.Length - 2, 2) + "元";
            OrderNumberTextBlock.Text = order.OrderId;
            PurchaseTime.Text = order.SubmitTime_dt.ToString("yyyy-MM-dd");
            IssuerTextBlock.Text = Setting.issuerName;
            string hiddenAccount = getHiddenAccount(Setting.account);
            //try
            //{
            //    int len = Setting.account.Length;
            //    hiddenAccount = Setting.account.Substring(0, 4) + " *** *** " + Setting.account.Substring(len - 4, 4);
            //}
            //catch { }
            //if (hiddenAccount == "")
            //{
            //    CardNumberTextBlock.Text = Setting.account;
            //    accountNumberTextBlock.Text = accountNumberTextBlock2.Text = Setting.account;
            //}
            //else
            //{
            CardNumberTextBlock.Text = hiddenAccount;
            accountNumberTextBlock.Text = accountNumberTextBlock2.Text = accountNumberTextBlock3.Text=hiddenAccount;
            
        }

        private string getHiddenAccount(string account)
        {

            string hiddenAccount = "";
            try
            {
                int len = account.Length;
                hiddenAccount = account.Substring(0, 4) + " *** *** " + account.Substring(len - 4, 4);
            }
            catch {
                hiddenAccount = account;
            }
            return hiddenAccount;

        }

        private void loadSelectCardPivot()
        {
            int limit = Convert.ToInt32(OrderClass.LimitedAmount);
            if (order.TransAmount < limit)
            {
                checkCodeTextBox.Visibility = Visibility.Collapsed;
                getCheckCodeButton.Visibility = Visibility.Collapsed;
                limitTextBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                int len = OrderClass.LimitedAmount.Length;
                limitTextBlock.Text = "  !  支付金额大于" + (limit / 100) + "." + OrderClass.LimitedAmount.Substring(len - 2, 2) + "元需要短信验证";
            }
        }

        private void loadCardInfoPivot()
        {
            bankTextBlock.Text = Setting.issuerName;
            int tempint = Convert.ToInt32(Setting.LimitedAmount),len=Setting.LimitedAmount.Length;
            tradeLimitTextBlock.Text ="剩余交易限额："+ (tempint/100)+"."+Setting.LimitedAmount.Substring(len-2,2)+"元";
            accountNumberTextBlock.Text = getHiddenAccount(Setting.account);
            string tempString = Setting.cardType;
            if ("CreditCard" == tempString) bankTextBlock.Text += "(信用卡)";
            else if ("DebitCard" == tempString) bankTextBlock.Text += "(借记卡)";
            else if ("PrepaidCard" == tempString) bankTextBlock.Text += "(储值卡)";
            else bankTextBlock.Text += "(未知类型卡)";
        }

        private void loadCardInfo2Pivot()
        {
            bankTextBlock2.Text = Setting.issuerName;
            int tempint = Convert.ToInt32(Setting.LimitedAmount), len = Setting.LimitedAmount.Length;
            tradeLimitTextBlock2.Text = "剩余交易限额：" + (tempint / 100) + "." + Setting.LimitedAmount.Substring(len - 2, 2) + "元";
            accountNumberTextBlock2.Text = getHiddenAccount(Setting.account);
            string tempString = Setting.cardType;
            if ("CreditCard" == tempString) bankTextBlock2.Text += "(信用卡)";
            else if ("DebitCard" == tempString) bankTextBlock2.Text += "(借记卡)";
            else if ("PrepaidCard" == tempString) bankTextBlock2.Text += "(储值卡)";
            else bankTextBlock2.Text += "(未知类型卡)";
        }

        private void loadCardInfo3Pivot()
        {
            bankTextBlock3.Text = Setting.issuerName;
            int tempint = Convert.ToInt32(Setting.LimitedAmount), len = Setting.LimitedAmount.Length;
            tradeLimitTextBlock3.Text = "剩余交易限额：" + (tempint / 100) + "." + Setting.LimitedAmount.Substring(len - 2, 2) + "元";
            accountNumberTextBlock3.Text = getHiddenAccount(Setting.account);
            phoneNumberTextBlock.Text = Setting.phoneNum;
            string tempString = Setting.cardType;
            if ("CreditCard" == tempString) bankTextBlock3.Text += "(信用卡)";
            else if ("DebitCard" == tempString) bankTextBlock3.Text += "(借记卡)";
            else if ("PrepaidCard" == tempString) bankTextBlock3.Text += "(储值卡)";
            else bankTextBlock3.Text += "(未知类型卡)";
        }

        private void loadResultPivot()
        {
            IssuerTextBlock.Text = Setting.issuerName;
            string hiddenAccount = getHiddenAccount(Setting.account); ;

            CardNumberTextBlock.Text = hiddenAccount;
         

 
        } 

        /*************************************************************/
        /*                                                           */
        /*                          返回                             */
        /*     由于不同应用程序可能有不同返回行为，所以这个函数用了委托    */
        /*     使得能从外界写一个函数,传进来，执行那个函数               */
        /*                                                           */
        /*************************************************************/
        public delegate bool CallBack(string result);
        public CallBack cb;
        public void setCallBack(CallBack cb) { this.cb = cb; }
        public void Return(string result)
        {
            if (this.cb != null)
            {
                try
                {
                    this.cb(result);
                }
                catch (Exception ccc)
                {
                    Console.WriteLine(ccc);
                }
            }
          
            
        }

        private void agreeHyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
           // pivotNum = 1;
            try
            {
                if (pivot.IsLocked)
                    pivot.IsLocked = false;
                pivot.SelectedIndex = 6;
                pivotNum = 6;
            }
            catch { }
            finally
            {
                pivot.IsLocked = true;
            }
        }

        private void agreeRadioButton_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
